from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename
import os
import datetime
import shutil
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 4096 * 1024 * 1024
# 设置用户名和密码
USERNAME = 'sumz'
PASSWORD = 'Sumz'
UPLOAD_FOLDER = 'D:\\JSONData\\SERVICE\\'
SYSNC_UPLOAD = 'D:\\JSONData\\SERVICE\\'

def authenticate(username, password):
    # 检查用户名和密码是否匹配
    if username == USERNAME and password == PASSWORD:
        return True
    return False


@app.route('/upload', methods=['POST'])
def upload_file():
    # 获取认证信息
    auth = request.authorization
    if not auth or not authenticate(auth.username, auth.password):
        # 返回未认证的错误响应
        return jsonify({'error': 'Unauthorized'}), 401

    # 检查是否上传了文件
    if 'file' not in request.files:
        return jsonify({'error': 'No file provided'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No file selected'}), 400

    # 确保文件名安全
    filename = secure_filename(file.filename)
    # filename = file.filename

    # 创建日期目录
    current_date = datetime.datetime.now().date()
    date_folder = os.path.join(UPLOAD_FOLDER, current_date.strftime("%Y%m%d"))
    os.makedirs(date_folder, exist_ok=True)

    # 保存文件
    #file.save(filename)
    file.save(os.path.join(date_folder, filename))

    return jsonify({'message': 'File uploaded successfully'})

@app.route('/sysnc_upload', methods=['POST'])
def sysnc_upload():
    # 获取认证信息
    auth = request.authorization
    if not auth or not authenticate(auth.username, auth.password):
        # 返回未认证的错误响应
        return jsonify({'error': 'Unauthorized'}), 401

    # 检查是否上传了文件
    if 'file' not in request.files:
        return jsonify({'error': 'No file provided'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No file selected'}), 400

    # 确保文件名安全
    # filename = secure_filename(file.filename)
    filename = file.filename

    filename = filename.replace("\\","/")

    directory_ = os.path.dirname(filename)
    filename_ = os.path.basename(filename)

    # 创建目录
    # current_date = datetime.datetime.now().date()
    date_folder = os.path.join(SYSNC_UPLOAD, directory_)
    os.makedirs(date_folder, exist_ok=True)

    # 保存文件
    #file.save(filename)
    # file.save(os.path.join(date_folder, filename_))
    file_path = os.path.join(date_folder, filename_)
    if os.path.exists(file_path):
        os.remove(file_path)
    with open(file_path, 'ab') as f:
        shutil.copyfileobj(file, f)

    print(f"保存文件：{file_path} 成功")
    return jsonify({'message': 'File uploaded successfully'})

# 返回服务器端文件列表
@app.route('/list_files', methods=['GET'])
def list_files():

    file_sysc_time = request.args.get('file_sync_time')
    client_name = request.args.get('client_name')

    file_list = []
    # 假如传入最小时间，否则全量返回
    if file_sysc_time:
        print(f"读取到最近同步时间:{file_sysc_time}")
        file_sysc_time = int(file_sysc_time)
        year = file_sysc_time // 10000
        month = (file_sysc_time // 100) % 100
        day = file_sysc_time % 100
        # year_directory = f"{year:04d}"
        # month_directory = f"{month:02d}"
        # day_directory = f"{day:02d}"

        zd_path = os.path.join(SYSNC_UPLOAD, client_name)
        os.makedirs(zd_path, exist_ok=True)

        zd_dir = os.listdir(zd_path)
        for zd_dir_one in zd_dir:
                if int(zd_dir_one) >= year:  # 循环年
                    yes_dir_path = os.path.join(zd_path, zd_dir_one)
                    for yes_dir_path_one in os.listdir(yes_dir_path):  # 循环月
                        if int(yes_dir_path_one) >= month:
                            month_dir_path = os.path.join(yes_dir_path, yes_dir_path_one)
                            for month_dir_path_one in os.listdir(month_dir_path):  # 循环日
                                if int(month_dir_path_one) >= day:
                                    day_dir_path = os.path.join(month_dir_path, month_dir_path_one)
                                    print("返回同步文件目录：%s" %day_dir_path)
                                    for root, dirs, files in os.walk(day_dir_path):
                                        for file in files:
                                            file_list.append(os.path.relpath(os.path.join(root, file), SYSNC_UPLOAD))
    else:
        for root, dirs, files in os.walk(SYSNC_UPLOAD):
            for file in files:
                file_list.append(os.path.relpath(os.path.join(root, file), SYSNC_UPLOAD))

    return jsonify(file_list)

if __name__ == "__main__":
    app.run(host='0.0.0.0')
